package chapter.tenth.item68;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

import org.perf4j.StopWatch;

public class ExecutorInstead {
	
	public static void main(String[] args) throws InterruptedException, ExecutionException {
		ExecutorService pool = Executors.newFixedThreadPool(3);
	
		ExecutorService scheduleService = new ScheduledThreadPoolExecutor(3, new RejectedExecutionHandler() {
			
			public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
				System.out.println(r.getClass());
			}
		});
		
		List<Runnable> tasks = new ArrayList<Runnable>();
		tasks.add(new Runnable(){
			public void run() {
				System.out.println("task1---,Thread: "+Thread.currentThread().getName());
			}
		});
		tasks.add(new Runnable(){
			public void run() {
				System.out.println("task2---,Thread: "+Thread.currentThread().getName());
			}
		});
		tasks.add(new Runnable(){
			public void run() {
				System.out.println("task3---,Thread: "+Thread.currentThread().getName());
			}
		});
		
		scheduleService.submit(tasks.get(1));
		scheduleService.submit(tasks.get(2));
		scheduleService.submit(tasks.get(0));
		System.out.println();
		StopWatch watch = new StopWatch();
		watch.start();
		//scheduleService.awaitTermination(1, TimeUnit.MINUTES);
		//System.out.println(watch.getElapsedTime());
		boolean is = scheduleService.isTerminated();
		System.out.println(is);
		while(!is){
			
			scheduleService.shutdown();
			if(!scheduleService.isTerminated()){
				System.out.println("未关闭。。。");
			}else{
				is = true;
				System.out.println("关闭。");
			}
		}
	}
}
